package cn.songtx.iot.config;

import cn.songtx.iot.pojo.*;
import cn.songtx.iot.service.*;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
@RequiredArgsConstructor
public class MqttConsumer {

    private final ISensorDhtService dhtService;
    private final ISensorAem1000Service aem1000Service;
    private final IDeviceMpptService deviceMpptService;
    private final IDeviceUpsService deviceUpsService;
    private final IDeviceEmService deviceEmService;
    private final ISysStatusService statusService;
    private final ISysCallbackService sysCallbackService;

    /*
     * 接收设备发送来的上行数据的时候执行,消费数据,使用MqttConfig配置类中的入站的消息通道
     */
    @Bean
    @ServiceActivator(inputChannel = "messageInputChannel")
    public MessageHandler messageHandler() {
        return this::mqttInterceptor;
    }

    /*
     *MQTT数据去SQL的拦截器
     * */
    public void mqttInterceptor(Message<?> message) {
        /*
         * 从MQTT的message包中解析Header和payload数据
         * 其中Header数据中包含mqtt_receivedRetained,id,mqtt_receivedTopic,Qos,timestamp等传输数据
         *   message数据中只包含payload数据
         * */
        String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
        Object payload = message.getPayload();

        /*
         * 根据主题写入SQL
         * Object对象解析为对应的实体类对象
         * 获取数据,抛出异常数据,如无异常写入数据库
         * payload对象需要解析为对应的实体类对象
         * */
        if (topic.matches("caihe/dht/(.*)")) {                             // dht
            SensorDht sensorDht = JSONObject.parseObject(payload.toString(), SensorDht.class);
            dhtService.save(sensorDht);
        } else if (topic.matches("caihe/aem1000/(.*)")) {                  // aem1000
            SensorAem1000 sensorAem1000 = JSONObject.parseObject(payload.toString(), SensorAem1000.class);
            aem1000Service.save(sensorAem1000);
        } else if (topic.matches("caihe/mppt/(.*)")) {                     // mppt
            DeviceMppt deviceMppt = JSONObject.parseObject(payload.toString(), DeviceMppt.class);
            deviceMpptService.save(deviceMppt);
        } else if (topic.matches("caihe/ups/(.*)")) {                      // ups
            DeviceUps deviceUps = JSONObject.parseObject(payload.toString(), DeviceUps.class);
            deviceUpsService.save(deviceUps);
        } else if (topic.matches("caihe/em/(.*)")) {                       // em
            DeviceEm deviceEm = JSONObject.parseObject(payload.toString(),DeviceEm.class);
            deviceEmService.save(deviceEm);
        } else if (topic.matches("caihe/100000000000000/(.*)")) {          // 下一个传感器
            log.info("备用");
        } else if (topic.matches("caihe/status")) {                        // status
            SysStatus sysStatus = JSONObject.parseObject(payload.toString(), SysStatus.class);
            statusService.save(sysStatus);
        } else if (topic.matches("caihe/callback/(.*)")) {                 // callback
            SysCallback callback = JSONObject.parseObject(payload.toString(), SysCallback.class);
            callback.setMac((topic.split("/"))[2]);                        // 从header中的topic解析出mad地址
            callback.setCallback(payload.toString());                            // 从payload中解析出callback
            sysCallbackService.save(callback);
        } else {
            log.info("未知的Topic:{}", topic);
        }
    }
}
